<template>
  <PageWrapper v-loading="loadingRef" contentFullHeight fixedHeight contentClass="flex">
    <DeviceGroupTree class="w-1/4 xl:w-1/5 mr-2" @select="handleSelect" />

    <PageWrapper contentFullHeight fixedHeight dense class="w-3/4 xl:w-4/5 overflow-hidden">
      <AdVxeTable @register="registerTable">
        <template #tools>
          <Authority :value="'Root.IoT.Admin.Device.Create'">
            <a-button type="primary" @click="handleCreate">
              <Icon icon="ant-design:plus-circle-outlined" />{{ t('common.addText') }}
            </a-button>
          </Authority>
        </template>

        <template #actionCol="{ row }">
          <TableAction
            outside
            :actions="[
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: t('common.delText'),
                auth: 'Root.IoT.Admin.Device.Delete', // 权限控制
                // ifShow: (_action) => {
                //   return row.Deletable === true; // 根据业务控制是否显示: 是否可删除的数据权限状态
                // },
                popConfirm: {
                  title: t('common.delConfirmText'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, row),
                },
              },
            ]"
            :dropDownActions="[
              {
                icon: 'clarity:details-line',
                label: t('common.detailText'),
                onClick: handleView.bind(null, row),
              },
              {
                icon: 'clarity:note-edit-line',
                label: t('common.editText'),
                auth: 'Root.IoT.Admin.Device.UpdateSimple', // 权限控制
                // ifShow: (_action) => {
                //   return row.Updatable === true; // 根据业务控制是否显示: 是否可更新的数据权限状态
                // },
                onClick: handleEdit.bind(null, row),
              },
              {
                icon: 'mdi:sign-real-estate',
                label: t('iot.route.state.device.title'),
                auth: 'Root.IoT.Admin.DeviceState.Read', // 权限控制
                // ifShow: (_action) => {
                //   return row.Updatable === true; // 根据业务控制是否显示: 是否可更新的数据权限状态
                // },
                onClick: handleState.bind(null, row),
              },
            ]"
          />
        </template>
      </AdVxeTable>
    </PageWrapper>

    <DeviceStateModal @register="registerStateFormModal" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import Icon from '@/components/Icon/Icon.vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Authority } from '@/components/Authority';
  import { AdVxeTable, useAdVxeTable, TableAction } from '@/components/AdVxeTable';

  import { useModal } from '@/components/AdVxeModal';

  import { FilterGroup, FilterRule } from '#/request';
  import { FilterOperateEnum } from '@/enums/filterOperateEnum';

  import {
    // getDeviceGroupNode,
    readDeviceSimple,
    createDevice,
    updateDeviceSimple,
    deleteDevice,
  } from '@/api/iot/admin/device';
  import { FormModeEnum } from '@/enums/formEnum';

  import DeviceGroupTree from '@/views/iot/device/group/DeviceGroupTree.vue';

  import { columns } from './device.data';
  import DeviceStateModal from './state.vue';

  defineOptions({ name: 'DevicePage' });

  const { t } = useI18n();
  const { createMessage } = useMessage();

  const groupId = ref<any>(null);

  const loadingRef = ref(false);
  function openWrapLoading() {
    loadingRef.value = true;
  }
  function closeWrapLoading() {
    loadingRef.value = false;
  }

  const [registerTable, { openDetailForm, reload, setProps }] = useAdVxeTable({
    id: 'iot-device-page-table',
    // 表标题呈现器
    title: t('iot.route.device.deviceList'),
    // 表格数据接口请求对象
    api: readDeviceSimple,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'iot_device_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('iot.route.device.title'),
      // 实体新增接口请求对象
      createApi: createDevice,
      // 实体更新接口请求对象
      updateApi: updateDeviceSimple,
    },
    // 表单列信息 AdColumn[]
    columns,
    // 使用搜索表单
    searchForm: true,
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  /** 处理组选择 */
  async function handleSelect(key: any, e: any) {
    // console.log('handleSelect', { key, e });
    groupId.value = key;
    let searchInfo: FilterGroup | null | undefined = undefined;
    if (key) {
      searchInfo = new FilterGroup();
      if (key === '0' || key === 0) {
        groupId.value = undefined;
        searchInfo.Rules.push(new FilterRule('DvcGrpId', null, FilterOperateEnum.Equal));
      } else {
        // const node = await getDeviceGroupNode(key);
        const node = e?.node;
        if (node) {
          // let filterRule = new FilterRule(
          //   'DvcGrpId',
          //   node.TreePathString,
          //   FilterOperateEnum.StartsWith,
          // );
          // filterRule.JoinEntityType = 'EaCloud.IoT.Entities.DeviceGroup,EaCloud.IoT.Core';
          // filterRule.JoinFilterField = 'TreePathString';
          // filterRule.JoinSelectField = 'Id';
          // searchInfo.value.Rules.push(filterRule);
          searchInfo.Rules.push(
            new FilterRule(
              'DvcGrp.TreePathString',
              node.TreePathString,
              FilterOperateEnum.StartsWith,
            ),
          );
        } else {
          searchInfo.Rules.push(new FilterRule('DvcGrpId', key, FilterOperateEnum.Equal));
        }
      }
    } else {
      searchInfo = null;
    }
    // @ts-ignore
    setProps({ searchInfo: searchInfo });
    reload();
  }

  /** 处理创建 */
  async function handleCreate() {
    openDetailForm(FormModeEnum.Add, { DvcGrpId: groupId.value });
  }
  /** 处理查看 */
  async function handleView(record: any) {
    openDetailForm(FormModeEnum.ReadOnly, record);
  }
  /** 处理编辑 */
  async function handleEdit(record: any) {
    openDetailForm(FormModeEnum.Edit, record);
  }
  /** 处理删除 */
  async function handleDelete(record: any) {
    // console.log(record);
    const result = await deleteDevice([record.Id]);
    if (result.Succeeded) {
      createMessage.success(t('common.successText'));
      reload();
    }
  }

  const [registerStateFormModal, stateFormModalMethods] = useModal();
  /** 处理查看状态 */
  async function handleState(record: any) {
    if (record && record.Id) {
      openWrapLoading();
      try {
        let searchInfo: FilterGroup = new FilterGroup();
        searchInfo.Rules.push(new FilterRule('DeviceId', record.Id, FilterOperateEnum.Equal));
        stateFormModalMethods.openModal(true, {
          searchInfo: searchInfo,
        });
      } finally {
        closeWrapLoading();
      }
    }
  }
</script>
